package com.java.simple.study.juc.p3.reentrant;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhoujl
 * @date 2022/5/10 21:59
 * @desc
 */
@Slf4j(topic = "c.TestTimeout")
public class TestTimeout {
    static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        //test1();
        test2();
    }

    public static void test2() {
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("尝试获取锁等待1s后仍未获取到失败！");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("尝试获取锁被打断");
                return;
            }
            try {
                log.debug("t1获取到了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("主线程获取到了锁");
        t1.start();
        try {
            Sleeper.sleep(2);
        } finally {
            lock.unlock();
        }
    }


    public static void test1() {
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            if (!lock.tryLock()) {
                log.debug("尝试获取锁 未获取到立刻返回false 快速失败！");
                return;
            }
            try {
                log.debug("t1获取到了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("主线程获取到了锁");
        t1.start();
        try {
            Sleeper.sleep(2);
        } finally {
            lock.unlock();
        }
    }

}
